<?php

if (!isset($_REQUEST['task']) || !is_numeric($_REQUEST['task'])) {
    error_obj::setError(new error_obj("bad request task", __FILE__, 'line 4 -> redirect'), UNEXCEPTED);
    base_obj::redirect(ROOT);
}

$taskId = (int) $_REQUEST['task'];

$client_obj = new client_obj();
$user_obj = new user_obj();
$task_obj = new task_obj();
$task_phorum_obj = new task_phorum_obj();
$record_obj = new record_obj();
$record_obj = new record_obj();
$tariff_obj = new tariff_obj();
$lock_obj = new lock_obj();

if (!$task_obj->visibleTask($taskId)) {
    error_obj::setError(new error_obj("not visible task", __FILE__, 'line 16 -> redirect'), UNEXCEPTED);
    base_obj::redirect(ROOT . '?input=list_of_tasks');
}

if (!empty($_REQUEST['result_message'])) {
    if ($_REQUEST['result_message'] == 'new_task')
        error_obj::setGood(ADDED_TASK);
    if ($_REQUEST['result_message'] == 'edit_task')
        error_obj::setGood(EDITED_TASK);
}

if (isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {
    switch ($_REQUEST['action']) {
        case 'edit_post':
            $phorum = $_REQUEST['phorum'];
            $phorum['text'] = base_obj::my_nl2br($phorum['text']);
            $keys = array('task_phorum_id' => $phorum['task_phorum_id']);
            unset($phorum['task_phorum_id']);
            $res = $task_phorum_obj->editPost($phorum, $keys);
            if (error_obj::isError($res)) {
                error_obj::setError($res, UNEXCEPTED);
            } else {
                base_obj::redirect(ROOT . '?input=edit_task&task=' . $taskId . '#' . $_REQUEST['phorum']['task_phorum_id']);
            }
            break;
        case 'add_record':

            $date = explode('/', $_REQUEST['record']['date']);
            $filter = array(
                'month' => $date[1],
                'year' => $date[2],
                'type' => 'record'
            );

            $is_locked = $lock_obj->getLocks($filter);
            if (error_obj::isError($is_locked)) {
                error_obj::setError($is_locked, UNEXCEPTED);
            } elseif (!empty($is_locked)) {
                error_obj::setError(new error_obj("locked record", __FILE__, ''), PERIOD_IS_LOCKED);
            } else {
                $in_data = $_REQUEST['record'];
                $in_data['unit_price'] = $in_data['price'];
                unset($in_data['price']);
                $in_data['date'] = base_obj::convertDateTo($in_data['date']);
                $in_data['taskId'] = $taskId;
                $newRecordId = $record_obj->addRecord($in_data);
                if (error_obj::isError(newRecordId)) {
                    error_obj::setError(newRecordId, UNEXCEPTED);
                } else {
                    $change_obj = new change_obj();
                    $in_data = array(
                        'rel_id' => $newRecordId,
                        'type' => CHANGES_TYPE_TSDR,
                        'status' => CHANGES_STATUS_NEW,
                        'date' => time()
                    );
                    $change_obj->add_change($in_data);
                    $task_obj->updateTaskRate($taskId);
                    base_obj::redirect(ROOT . '?input=edit_task&task=' . $taskId);
                }
            }
            break;
        case 'edit_record':
            $recordId = (int) $_REQUEST['recordId'];
            if (empty($recordId))
                break;
            $originalRecord = $record_obj->getRecordById($recordId);
            $in_data = $_REQUEST['record'];
            $in_data['unit_price'] = $in_data['price'];
            unset($in_data['price']);
            $in_data['date'] = base_obj::convertDateTo($in_data['date']);
            if (!isset($in_data['after_hours']))
                $in_data['after_hours'] = 0;
            $result = $record_obj->editRecord($in_data, $recordId);
            if (error_obj::isError($result)) {
                error_obj::setError($result, UNEXCEPTED);
            } else {
                $change_obj = new change_obj();
                $change_obj->add_change_with_records_compare($recordId, $originalRecord);

                $task_obj->updateTaskRate($taskId);
                base_obj::redirect(ROOT . '?input=edit_task&task=' . $taskId);
            }
            break;
    }
    $actions = explode("_", $_REQUEST['action']);
    if (in_array(TASK_ACTION_WRITE, $actions)) {

        $task = $_REQUEST['task_data'];
        $task['updated'] = date("Y-m-d H:i:s");
        $task['updater'] = $_SESSION['user']['user_id'];
        if (!empty($task['task_start']))
            $task['task_start'] = base_obj::convertDateTo($task['task_start']);
        if ($task['deadline'] == '00/00/0000')
            $task['deadline'] = MAX_DEADLINE;
        $task['deadline'] = base_obj::convertDateTo($task['deadline']);

        if (!isset($task['consult']))
            $task['consult'] = 0;

        if (!empty($_REQUEST['phorum']['text'])) {
            $task_phorum = $_REQUEST['phorum'];
            $task_phorum['user_id'] = $_SESSION['user']['user_id'];
            $task_phorum['when'] = date("Y-m-d H:i:s");
            $task_phorum['task_id'] = $taskId;
            $task_phorum['text'] = base_obj::my_nl2br($task_phorum['text']);

            $res = $task_phorum_obj->addPost($task_phorum);
            if (error_obj::isError($res)) {
                error_obj::setError($res, UNEXCEPTED);
            } else {
                $flag_new_post_added = true;
            }
        }

        if (in_array(TASK_ACTION_COMPLETE, $actions))
            $task['status'] = COMPLETED_TASK;

        $originalTask = array();
        //if (in_array(TASK_ACTION_SEND, $actions))
        $originalTask = $task_obj->getTaskById($taskId);

        $result = $task_obj->editTask($task, $taskId);
        if (error_obj::isError($result)) {
            error_obj::setError($result, UNEXCEPTED);
        } else {
            $task_obj->updateTaskRate($taskId);
            if ((in_array(TASK_ACTION_COMPLETE, $actions) || $task['status'] == COMPLETED_TASK) && ($_REQUEST['oldStatus'] != COMPLETED_TASK)) {
                $task_phorum = array();
                $task_phorum['task_id'] = $taskId;
                $task_phorum['user_id'] = $_SESSION['user']['user_id'];
                $task_phorum['when'] = date("Y-m-d H:i:s");
                $task_phorum['text'] = 'Completed';
                $res = $task_phorum_obj->addPost($task_phorum);
                if (error_obj::isError($res)) {
                    error_obj::setError($res, UNEXCEPTED);
                }
            }

            if ($task['type'] == 9) {
                $operation = $_REQUEST['operation'];
                $operation['date_of_action'] = base_obj::convertDateTo($operation['date_of_action']);
                $operation['taskId'] = $taskId;
                $res = $task_obj->addOperationWithUser($operation, $taskId);
                if (error_obj::isError($res)) {
                    error_obj::setError($res, UNEXCEPTED);
                }
            } elseif ($task['type'] == 8) {
                $goods = $_REQUEST['goods'];
                $goods['delivery'] = base_obj::convertDateTo($goods['delivery']);
                $goods['taskId'] = $taskId;
                $res = $task_obj->addOrderOfGoods($goods, $taskId);
                if (error_obj::isError($res)) {
                    error_obj::setError($res, UNEXCEPTED);
                }
            }
            
            //$_SESSION['request']['client'] = $task['client'];
            if (!empty($_REQUEST['phorum']['text'])) {
                $task['post'] = $_REQUEST['phorum']['text'];
            }
            if (in_array(TASK_ACTION_SEND, $actions)) {
                $sent = $task_obj->send_notification($taskId, $task, 'edit', $originalTask, true);
            } else {
                $sent = $task_obj->send_notification($taskId, $task, 'edit', $originalTask);
            }
            if (error_obj::isError($sent))
                error_obj::setError($sent, EMAIL_ERROR_NOT_SENT);
            
            $change_obj = new change_obj();
            $change_obj->add_change_with_tasks_compare($taskId, $originalTask);
            
            base_obj::redirect(ROOT . '?input=edit_task&task=' . $taskId . '&result_message=edit_task');
        }
    }
}
$task_data = $task_obj->getTaskById($taskId);

if (error_obj::isError($task_data))
    error_obj::setError($task_data, UNEXCEPTED);
elseif (empty($task_data))
    error_obj::setError(new error_obj("empty task", __FILE__, 'get task data'), EMPTY_TASK);
else {
    $task = array();
    $filter = array();
    $filter['active'] = 0;
    if ($_SESSION['user']['profile']['userlevel'] == USER_TYPE_CLIENT) {
        $filter['clients'] = $_SESSION['user']['clients'];
    }
    $task['clients'] = $client_obj->getAllClients('contactPerson, klient_id, name, bad_payer', $filter, 'name ASC');
    $filter = array();
    $filter['active'] = 1;
    $filter['client'] = 11;
    $task['responsibles'] = $user_obj->getUsers('name, surname, users_id', $filter);
    $task['types'] = $task_obj->getTaskTypes();
    $task['statuses'] = $task_obj->getTaskStatuses();
    $task['priorities'] = $task_obj->getTaskPriorities();
    $task['problem_types'] = $task_obj->getTaskTypeOfProblems();
    $task['operation_types'] = $task_obj->getTaskTypeOfOperations();
    $task['goods_types'] = $task_obj->getGoodTypes();


    $GLOBALS['template_data'] = $task;

    $GLOBALS['template_data']['task_data'] = $task_data;
    if (!empty($GLOBALS['template_data']['task_data']['task_start']))
        $GLOBALS['template_data']['task_data']['task_start'] = base_obj::convertDateTo($GLOBALS['template_data']['task_data']['task_start'], 'dd/mm/yyyy', 'date');
    else
        $GLOBALS['template_data']['task_data']['task_start'] = "";
    $GLOBALS['template_data']['task_data']['deadline'] = base_obj::convertDateTo($GLOBALS['template_data']['task_data']['deadline'], 'dd/mm/yyyy', 'date');
    if ($GLOBALS['template_data']['task_data']['deadline'] == MAX_DEADLINE)
        $GLOBALS['template_data']['task_data']['deadline'] = '00/00/0000';
    if ($GLOBALS['template_data']['task_data']['type'] == 8) {
        $GLOBALS['template_data']['task_data']['order_of_goods'] = $task_obj->getOrderOfGoods($task_data['taskId']);
        $GLOBALS['template_data']['task_data']['order_of_goods']['delivery'] = base_obj::convertDateTo($GLOBALS['template_data']['task_data']['order_of_goods']['delivery'], 'dd/mm/yyyy', 'date');
    }
    if ($GLOBALS['template_data']['task_data']['type'] == 9) {
        $GLOBALS['template_data']['task_data']['operation_with_user'] = $task_obj->getOperationWithUser($task_data['taskId']);
        $GLOBALS['template_data']['task_data']['operation_with_user']['date_of_action'] = base_obj::convertDateTo($GLOBALS['template_data']['task_data']['operation_with_user']['date_of_action'], 'dd/mm/yyyy', 'date');
    }
    $filter = array();
    $filter['task_id'] = $task_data['taskId'];
    $GLOBALS['template_data']['task_data']['phorum'] = $task_phorum_obj->getPostsInPhorum($filter, "'when' ASC");
    foreach ($GLOBALS['template_data']['task_data']['phorum'] as $key => $post) {
        $GLOBALS['template_data']['task_data']['phorum'][$key]['text'] = htmlspecialchars_decode($GLOBALS['template_data']['task_data']['phorum'][$key]['text']);
        //$GLOBALS['template_data']['task_data']['phorum'][$key]['text'] = str_replace("<", "&lt;", $GLOBALS['template_data']['task_data']['phorum'][$key]['text']);
        //$GLOBALS['template_data']['task_data']['phorum'][$key]['text'] = str_replace(">", "&gt;", $GLOBALS['template_data']['task_data']['phorum'][$key]['text']);
        $GLOBALS['template_data']['task_data']['phorum'][$key]['when'] = base_obj::convertDateTo($post['when'], 'dd/mm/yyyy H:i:s', 'datetime');
        $GLOBALS['template_data']['task_data']['phorum'][$key]['user_data'] = $user_obj->getUserById($post['user_id'], array('name', 'surname'));
    }

    $filter = array();
    $filter['taskId'] = $task_data['taskId'];
    $records = $record_obj->getListOfRecords($filter, array('col' => 'date', 'orderBy' => 'date', 'order' => 'DESC', 'table' => '', 'connector' => ''));

    foreach ($records as $key => $record) {
        $records[$key]['date_formated'] = base_obj::convertDateTo($record['date'], 'dd/mm/yyyy H:i:s', 'datetime');
        $records[$key]['locked'] = 0;
        if ($lock_obj->isRecordLocked($records[$key]['date_formated'])) {
            $records[$key]['locked'] = 1;
        }
        $records[$key]['client_info'] = $client_obj->getClient($record['client']);
        $records[$key]['type_info'] = $record_obj->getTypeOfRecordById($record['type']);
        $records[$key]['user_info'] = $user_obj->getUserById($record['user_id']);
        if ($record['tariff'] != -1)
            $records[$key]['tariff_info'] = $tariff_obj->getTariffById($record['tariff']);
    }
    $GLOBALS['template_data']['task_data']['records'] = $records;
    /////////////// end of task data
    /////////////// start of record data
    $GLOBALS['template_data']['rtypes'] = $record_obj->getRecordTypes();
    $filter = array();
    $filter['type_of_record'] = $GLOBALS['template_data']['task_data']['type'];
    $GLOBALS['template_data']['rtariffs'] = $tariff_obj->getTariffs("Id, title", $filter, array('col' => 'title', 'orderBy' => 'title', 'order' => 'ASC', 'table' => '', 'connector' => ''));
    $filter = array(
        'client' => 11,
        'active' => 1
    );
    $GLOBALS['template_data']['rusers'] = $user_obj->getUsers('users_id, name, surname', $filter);
    $GLOBALS['template_data']['isCopy'] = 0;
    if (isset($_REQUEST['copy_id']) && !empty($_REQUEST['copy_id']) && is_numeric($_REQUEST['copy_id'])) {
        $toCopy = $record_obj->getRecordById($_REQUEST['copy_id']);
        if (!error_obj::isError($toCopy) && !empty($toCopy)) {
            $filter = array();
            $filter['type_of_record'] = $toCopy['type'];
            $GLOBALS['template_data']['rtariffs'] = $tariff_obj->getTariffs("Id, title", $filter, array('col' => 'title', 'orderBy' => 'title', 'order' => 'ASC', 'table' => '', 'connector' => ''));
            $GLOBALS['template_data']['prefill'] = $toCopy;
            $GLOBALS['template_data']['prefill']['date'] = base_obj::convertDateTo($GLOBALS['template_data']['prefill']['date'], "dd/mm/yyyy", 'date');
            $GLOBALS['template_data']['isCopy'] = 1;
        }
    }

    if ($GLOBALS['template_data']['isCopy'] != 1) {
        $filter = array();
        $filter['type_of_record'] = $GLOBALS['template_data']['task_data']['type'];
        $GLOBALS['template_data']['rtariffs'] = $tariff_obj->getTariffs("Id, title", $filter, array('col' => 'title', 'orderBy' => 'title', 'order' => 'ASC', 'table' => '', 'connector' => ''));
        $GLOBALS['template_data']['prefill']['user_id'] = $_SESSION['user']['user_id'];
        $GLOBALS['template_data']['prefill']['date'] = date("d/m/Y");
        $GLOBALS['template_data']['prefill']['description'] = $GLOBALS['template_data']['task_data']['title'];
        $GLOBALS['template_data']['prefill']['client'] = $GLOBALS['template_data']['task_data']['client'];
        $GLOBALS['template_data']['prefill']['amount'] = $GLOBALS['template_data']['task_data']['duration'];
        $GLOBALS['template_data']['prefill']['type'] = $GLOBALS['template_data']['task_data']['type'];
        if ($GLOBALS['template_data']['prefill']['type'] == 3 || $GLOBALS['template_data']['prefill']['type'] == 4) {
            $tariff_title = $tariff_obj->getTariffs('title', array('type_of_record' => $GLOBALS['template_data']['prefill']['type']));
            $GLOBALS['template_data']['prefill']['description'] = $tariff_title['title'];
        }
    }

    if (isset($_REQUEST['editRecord']) && !empty($_REQUEST['editRecord']) && is_numeric($_REQUEST['editRecord'])) {
        $toEdit = $record_obj->getRecordById($_REQUEST['editRecord']);
        if ($lock_obj->isRecordLocked(base_obj::convertDateTo($toEdit['date'], "dd/mm/yyyy", 'date'))) {
            error_obj::setError(new error_obj("locked record", __FILE__, ''), PERIOD_IS_LOCKED);
            $_REQUEST['editRecord'] = -1;
        } else {
            if (!error_obj::isError($toEdit) && !empty($toEdit)) {
                $filter = array();
                $filter['type_of_record'] = $toEdit['type'];
                $GLOBALS['template_data']['rtariffs_edit'] = $tariff_obj->getTariffs("Id, title", $filter, array('col' => 'title', 'orderBy' => 'title', 'order' => 'ASC', 'table' => '', 'connector' => ''));
            }
        }
    }
}
?>
